package com.ossjk.qlh.system.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ossjk.config.os.COSClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ossjk.core.base.controller.BaseController;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.core.util.EncryptUtil;
import com.ossjk.core.util.JwtTokenUtil;
import com.ossjk.core.util.OsUtil;
import com.ossjk.core.vo.RequestBean;
import com.ossjk.core.vo.ResponseBean;
import com.ossjk.qlh.loginfo.LogModule;
import com.ossjk.qlh.loginfo.LogOperation;
import com.ossjk.qlh.system.entity.Department;
import com.ossjk.qlh.system.entity.Dictionary;
import com.ossjk.qlh.system.entity.Findpwd;
import com.ossjk.qlh.system.entity.Loginrecord;
import com.ossjk.qlh.system.entity.Permission;
import com.ossjk.qlh.system.entity.Role;
import com.ossjk.qlh.system.entity.Token;
import com.ossjk.qlh.system.entity.User;
import com.ossjk.qlh.system.service.IDepartmentService;
import com.ossjk.qlh.system.service.IDictionaryService;
import com.ossjk.qlh.system.service.IFindpwdService;
import com.ossjk.qlh.system.service.ILoginrecordService;
import com.ossjk.qlh.system.service.IPermissionService;
import com.ossjk.qlh.system.service.IRoleService;
import com.ossjk.qlh.system.service.ITokenService;
import com.ossjk.qlh.system.service.IUserService;
import com.ossjk.qlh.system.vo.UserVo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@LogModule(value = "基础管理")
@Api(tags = "基础管理")
@RestController
@RequestMapping("/")
public class IndexController extends BaseController {

	@Autowired
	private IUserService iUserService;
	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	@Autowired
	private ITokenService iTokenService;
	@Autowired
	private IPermissionService iPermissionService;
	@Autowired
	private IRoleService iRoleService;
	@Autowired
	private ILoginrecordService iLoginrecordService;
	@Autowired
	private IDepartmentService iDepartmentService;
	@Autowired
	private IDictionaryService iDictionaryService;
	@Autowired
	private IFindpwdService iFindpwdService;
	@Autowired
	private MailAccount mailAccount;

	@Value("${server.port}")
	private String serverport;

	@Value("${server.servlet.context-path}")
	private String paths;

	@Value("${fconfig.upload}")
	private String uploadfile;

	@Value("${fconfig.address}")
	private String serveraddress;

	@ApiOperation(value = "文件上传")
	@PostMapping(value = "/fileUpload")
	@ResponseBody
	public ResponseBean upload(HttpServletRequest request) throws IllegalStateException, IOException {
		COSClientUtil cosClientUtil = new COSClientUtil();

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		// 获取上传的文件
		MultipartFile file = multipartRequest.getFile("file");

		// 测试MultipartFile接口的各个方法
		System.out.println("文件类型ContentType=" + file.getContentType());
		System.out.println("文件组件名称Name=" + file.getName());
		System.out.println("文件原名称OriginalFileName=" + file.getOriginalFilename());
		System.out.println("文件大小Size=" + file.getSize() / 1024 + "KB");

		// 如果文件不为空，写入上传路径，进行文件上传
		if (!file.isEmpty()) {

			// 构建上传文件的存放路径
			String path = request.getServletContext().getRealPath(uploadfile);
			System.out.println("path = " + path);


			// 获取上传的文件名称，并结合存放路径，构建新的文件名称
			String filename = file.getOriginalFilename();

			// 随机生成文件名，使用时间戳
			String hz = filename.substring(filename.lastIndexOf("."));
			String filename2 = new Date().getTime() + hz;

			File filepath = new File(path, filename2);

			// 判断路径是否存在，不存在则新创建一个
			if (!filepath.getParentFile().exists()) {
				filepath.getParentFile().mkdirs();
			}

			// 将上传文件保存到目标文件目录
			file.transferTo(new File(path + File.separator + filename2));
			System.out.println("文件现名称=" + filename2);

			cosClientUtil.destory();
			cosClientUtil.cosclient.shutdown();
			String url = serveraddress+":" + serverport  + paths + uploadfile + filename2;
			System.out.println("------------------------------------url--------------"+url);
			return responseSuccess( "上传成功",url);
		} else {

			return responseFail("上传失败");
		}

	}


	@ApiOperation(value = "登录")
	@ApiImplicitParams({ @ApiImplicitParam(name = "lname", value = "登录名", required = true, paramType = "query"), @ApiImplicitParam(name = "pwd", value = "密码", required = true, paramType = "query") })
	@PostMapping(value = "/login")
	public ResponseBean login(@RequestBody RequestBean<User> requestBean, HttpServletRequest request) {
		// 生成登录日志
		Loginrecord loginrecord = new Loginrecord();
		loginrecord.setUseragent(request.getHeader("User-Agent"));
		Date date = new Date();
		loginrecord.setLogintime(date);
		// 登录是否成功 1-成功 2-失败
		loginrecord.setLoginresult(2);
		loginrecord.setIp(OsUtil.getCliectIp(request));

		User user = requestBean.getData();
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.eq("lname", user.getLname()).or().eq("mobile", user.getLname()).or().eq("email", user.getLname());
		User user2 = iUserService.getOne(queryWrapper);
		if (!CommonUtil.isBlank(user2)) {
			loginrecord.setUid(user2.getId());
			loginrecord.setCrer(user2.getId());
			loginrecord.setMder(user2.getId());
			if (CommonUtil.isEquals(user2.getPwd(), EncryptUtil.MD5(user.getPwd()))) {
				// 生成token
				String tokenStr = jwtTokenUtil.generalToken(user2.getId(), user2.getName());
				Token token = new Token();
				token.setUid(user2.getId());
				token.setToken(tokenStr);
				token.setDuration(jwtTokenUtil.getTokenTimeOut(tokenStr));
				token.setCrer(user2.getId());
				token.setMder(user2.getId());
				// 查找权限编码
				Map<String, Object> expressionMap = new HashMap<String, Object>();
				expressionMap.put("codes", iPermissionService.listUserPermissionCodeByUid(user2.getId()));
				expressionMap.put("rids", iRoleService.listUserRidByUid(user2.getId()));
				expressionMap.put("dids", iDepartmentService.listUserDidByUid(user2.getId()));
				token.setExpression(JSON.toJSONString(expressionMap));
				iTokenService.save(token);
				expressionMap.clear();
				// 登录是否成功 1-成功 2-失败
				loginrecord.setLoginresult(1);
				iLoginrecordService.save(loginrecord);
				return responseSuccess("登录成功", tokenStr);
			} else {
				iLoginrecordService.save(loginrecord);
				return responseFail("密码错误。");
			}
		} else {
			return responseFail("用户不存在。");
		}
	}

	@ApiOperation(value = "登出")
	@PostMapping(value = "/logout")
	public ResponseBean logout() {
		QueryWrapper<Token> queryWrapper = new QueryWrapper<Token>();
		queryWrapper.eq("token", getToken());
		iTokenService.remove(queryWrapper);
		return responseSuccess("已退出登录");
	}

	@LogOperation("发送邮件")
	@ApiOperation(value = "发送邮件")
	@PostMapping(value = "/sendEmail")
	public ResponseBean sendEmail(@RequestBody RequestBean<Map<String, String>> requestBean) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.eq("email", requestBean.getData().get("email"));
		User user = iUserService.getOne(queryWrapper);
		if (!CommonUtil.isBlank(user)) {
			Findpwd findpwd = new Findpwd();
			findpwd.setUid(user.getId());
			// 验证码
			int code = (int) ((Math.random() * 9 + 1) * 100000);
			findpwd.setCode(String.valueOf(code));
			// 失效时间
			int time = 70;
			Date duration = new Date(new Date().getTime() + time * 1000);
			findpwd.setDuration(duration);
			iFindpwdService.save(findpwd);
			String message = "验证码：" + code + "，有效时间：" + (time - 10) + "秒";
			try {
				MailUtil.send(mailAccount, CollUtil.newArrayList(user.getEmail()), "验证码", message, false);
				return responseSuccess("已将密码发送至邮箱，请前往查看");
			} catch (Exception e) {
				return responseException("发送邮件异常，请联系管理员检查参数。");
			}

		} else {
			return responseFail("用户不存在。");
		}
	}

	@LogOperation("找回密码")
	@ApiOperation(value = "找回密码")
	@PostMapping(value = "/findPwd")
	public ResponseBean findPwd(@RequestBody RequestBean<Map<String, String>> requestBean) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.eq("email", requestBean.getData().get("email"));
		User user = iUserService.getOne(queryWrapper);
		// 判断邮箱是否正确
		if (!CommonUtil.isBlank(user)) {
			QueryWrapper<Findpwd> queryWrapper2 = new QueryWrapper<Findpwd>();
			queryWrapper2.eq("uid", user.getId()).eq("code", requestBean.getData().get("code"));
			Findpwd findpwd = iFindpwdService.getOne(queryWrapper2);
			// 判断验证码是否正确
			if (!CommonUtil.isBlank(findpwd)) {
				// 判断验证码是否已失效
				if (new Date().getTime() <= findpwd.getDuration().getTime()) {
					user.setPwd(EncryptUtil.MD5(requestBean.getData().get("newPwd")));
					if (iUserService.updateById(user)) {
						return responseSuccess("修改密码成功，即将跳转去登录");
					} else {
						return responseFail();
					}
				} else {
					return responseFail("验证码已失效！");
				}

			} else {
				return responseFail("验证码错误");
			}
		} else {
			return responseFail("用户不存在。");
		}
	}

	/**
	 * 获取用户信息
	 *
	 * @return
	 */
	/**
	 * @return
	 */
	@ApiOperation(value = "获取用户信息")
	@PostMapping(value = "/getInfo")
	public ResponseBean getInfo() {

		Map<String, Object> data = new HashMap<String, Object>();
		// 获取用户id
		String uid = getUid();
		// 获取用户信息
		UserVo userVo = iUserService.getInfoById(uid);
		// 获取权限菜单
		List<Permission> permissions = iPermissionService.listUserPermissionByUid(uid);
		// 获取角色列表
		List<Role> roleChildren = new ArrayList<Role>();
		roleChildren = iRoleService.queryChildrenByPid(userVo.getRid(), roleChildren);
		// 获取部门列表
		List<Department> departmentChildren = new ArrayList<Department>();
		departmentChildren = iDepartmentService.queryChildrenByPid(userVo.getDid(), departmentChildren);
		data.put("userVo", userVo);
		data.put("permissions", permissions);
		data.put("roleChildren", roleChildren);
		data.put("departmentChildren", departmentChildren);
		return responseSuccess(data);
	}

	@ApiOperation(value = "获取系统配置")
	@PostMapping(value = "/getSystemsetting")
	public ResponseBean<List<Dictionary>> getSystemsetting() {
		QueryWrapper<Dictionary> queryWrapper = new QueryWrapper<Dictionary>();
		queryWrapper.eq("type", 2);
		return responseSuccess(iDictionaryService.list(queryWrapper));
	}

}
